const { get, post } = require('../utils/http')
const { appid, secret, url } = require('../config')
const { getTimestamp, getRandomStr } = require('../utils/tools')
const crypto = require('crypto')
const db = require('../utils/db')

const getToken = async () => {
  let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`
  let rs = await get(url);
  return rs.data.access_token;
}

const getTicket = async (access_token) => {
  let url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`
  let rs = await get(url);
  return rs.data;
}

module.exports = async (ctx) => {

  let token;
  let ticket;
  let expires_in;

  //先查询数据库，如果数据库有access_token且未过期，就不用在生成，否则就生成

  //1：先查询数据库
  let rs = await db("select * from token")
  console.log('db select result:', rs);
  let timestamp = getTimestamp();
  if (!rs.length) {
    //如果数据不存在数据的话，就插入数据
    token = await getToken()
    console.log('token:', token)
    let tmp = await getTicket(token);
    ticket = tmp.ticket;
    expires_in = tmp.expires_in;
    console.log('ticket:', ticket)
    let result = await db("insert into token set ? ", { access_token: token, ticket, expires_in, start_time: timestamp })
  } else {
    let start_time = rs[0].start_time;
    let expires_in = rs[0].expires_in
    //判断时间是否过期
    if (timestamp - start_time > expires_in) {
      //数据已经过期
      token = await getToken()
      let tmp = await getTicket(token);
      ticket = tmp.ticket;
      expires_in = tmp.expires_in;
      //更新数据库
      await db('update token set access_token = ?,ticket=? ,expires_in=?,start_time=?',[token,ticket,expires_in,timestamp])

    } else {
      token = rs[0].access_token;
      ticket = rs[0].ticket;
    }
  }

  let noncestr = getRandomStr(16);
  let string1 = `jsapi_ticket=${ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}`
  //生成签名
  let signature = crypto.createHash('sha1').update(string1).digest('hex')

  ctx.body = {
    appid,
    timestamp,
    noncestr,
    signature
  };
}